import base64
import os
import shutil
import time
from io import open
import fitz
import requests





def general_word(file):
    general_word_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"  # 高精度 500次每天
    # general_word_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic" # 标准 50000次/天
    # general_word_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard" # 标准 50000次/天
    # 二进制方式打开图片文件
    f = open(file, 'rb')
    img = base64.b64encode(f.read())
    params = {"image": img, "language_type": "CHN_ENG", }
    access_token = get_access_token()
    request_url = general_word_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    try:
        if response.json()["error_msg"] == 'internal error':
            response = requests.post(request_url, data=params, headers=headers)
    except:
        pass
    return response


# 3.上传png图片获取文字内容
def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {
        'grant_type': 'client_credentials',  # 固定值
        'client_id': 'oNL5naGKSne8UNAXxlA0e83l',  # 在开放平台注册后所建应用的API Key
        'client_secret': 'gbLkZHg4irE5O80UlOSfCx2omhkyCYSL'  # 所建应用的Secret Key
    }
    res = requests.post(url, data=data)
    res = res.json()
    access_token = res['access_token']
    return access_token


def file_name(file_dir):
    """ root： 当前目录路径
        dirs： 当前路径下所有子目录
        files：当前路径下所有非目录子文件
    """
    for root, dirs, files in os.walk(file_dir):
        return files


def start_identify(file_path):
    output_path = os.path.join(os.getcwd(), '图片临时文件夹')
    if os.path.exists(output_path):
        shutil.rmtree(output_path)
    os.mkdir(output_path)
    Li = []
    for file_name in os.listdir(file_path):
        if '办理登记手续通知书' in file_name:
            file_full_path = os.path.join(file_path, file_name)
            img_path = pdf_to_img(file_full_path, output_path, file_name)
            response = general_word(img_path)       # 百度接口解析pdf
            ordr_number = file_name.split("_")[1]
            if response:
                item = parse_response(response, img_path)
                item1 = parse_item_new(item)
                item1["ordr_number"] = ordr_number
                item1["fwr"] = file_name.split("_")[0]
                item1["inst"] = file_name.split("_")[-1].split(".")[0]
                item1["sqr"] = file_name.split("_")[0]
                item1["zl_type"] = "发明专利" if item1["申请号"][4] == "1" else "实用新型专利" if item1["申请号"][4] == "2" else "外观设计专利"
            else:
                item1 = {}
                item1['申请号'] = file_name.split('_')[-2].split('-')[0]
                item1['专利权人'] = ''
                item1["inst"] = file_name.split("_")[-1].split(".")[0]
                item1['发明名称'] = file_name.split('_')[-4]
                item1['截止日'] = ''
                item1['总计'] = ''
                item1['已缴费'] = ''
                item1['相等'] = ''
                item1['备注'] = '未识别到'
                item1['插入时间'] = time.strftime("%Y-%m-%d %H:%M:%S")
                item1['费用明细'] = ''
                item1["ordr_number"] = ordr_number
                item1["fwr"] = file_name.split("_")[1]
                item1["sqr"] = file_name.split("_")[0]
                item1["zl_type"] = ''
                print('未识别成功')
            Li.append(item1)
    return Li


def pdf_to_img(file_full_path, output_path, file_name):
    doc = fitz.open(file_full_path)
    page = doc.loadPage(0)  # PDF页数
    pix = page.getPixmap()
    png_name = file_name.split('.')[0] + '.png'
    img_path = os.path.join(output_path, png_name)
    pix.writePNG(img_path)  # 保存
    return img_path


def parse_item_new(item):
    item1 = {}
    item1['申请号'] = item['申请号']
    item1['专利权人'] = item['专利权人']
    item1['发明名称'] = item['发明名称']
    item1['截止日'] = item['截止日'].replace('年', '-').replace('月', '-').replace('日', '')
    item1['总计'] = item['总计']
    item1['已缴费'] = item['已缴费']
    item1['相等'] = item['相等']
    item1['备注'] = item['备注']
    key_list = ['申请号', '专利权人', '发明名称', '截止日', '总计', '已缴费', '相等', '备注']
    money_li = []
    for key, value in item.items():
        if key not in key_list:
            money_detail_str = str(key) + str(value)
            money_li.append(money_detail_str)
    money_str = '+'.join(money_li)
    item1['插入时间'] = time.strftime("%Y-%m-%d %H:%M:%S")
    item1['费用明细'] = money_str
    return item1


def parse_response(response, file):
    res = response.json()["words_result"]
    item = {}
    item['备注'] = ''
    item['相等'] = ''

    money_li = []
    is_start = False
    for word_dict in res:
        words = word_dict['words']
        if '申请号或专利号:' in words:
            item['申请号'] = words.split(':')[-1].replace('.', '')
            file_sqh = file.split('_')[-2].split('-')[0]
            if item['申请号'] != file_sqh:
                item['备注'] = '申请号:{}读取不正确,取文件名中申请号'.format(item['申请号'])
                item['申请号'] = file_sqh
        if '申请人或专利权人:' in words:
            item['专利权人'] = words.split(':')[-1]
        if '申请人或专利权人：' in words:
            item['专利权人'] = words.split('：')[-1]
        if '发明创造名称:' in words:
            item['发明名称'] = words.split(':')[-1]
            file_fm_name = file.split('_')[-4]
            if item['发明名称'] != file_fm_name:
                item['备注'] = '专利名称:{}读取不正确,取文件名中专利名称'.format(item['发明名称'])
                item['发明名称'] = file_fm_name
        if '申请人应当于' in words:
            item['截止日'] = words.split('申请人应当于')[-1]
        if is_start:
            money_li.append(words)
        if '之前缴纳以下费用' in words:
            is_start = True
        if '附已缴费用情况:' in words:
            is_start = False
        if '附已缴费用情况：' in words:
            is_start = False
    money_number = 0
    for i in range(len(money_li)):
        if '元' in money_li[i]:
            if '缴费用情况' in money_li[i]:
                if ':' in money_li[i]:
                    item['已缴费'] = money_li[i].split(':')[-1].replace('专利证书', '').replace('。', '')
                else:
                    item['已缴费'] = money_li[i].split('：')[-1].replace('专利证书', '').replace('。', '')
            else:
                if money_li[i - 1] == '共计':
                    item['总计'] = money_li[i]
                else:
                    item[money_li[i - 1].replace('专利证书', '')] = money_li[i]
                if money_li[i - 1] != '共计' and money_li[i - 1] != '总计':
                    money_number += int(float(money_li[i].replace('元', '')))
    item['总计'] = money_number

    if '总计' in item.keys():
        if money_number == int(float(item['总计'])):
            item['相等'] = '是'
        else:
            item['相等'] = '否'
    else:
        item['总计'] = '?'
        item['相等'] = '?'

    if '截止日' not in item.keys():
        item['截止日'] = '?'
    if '发明名称' not in item.keys():
        item['发明名称'] = file.split('_')[-4]
    if '专利权人' not in item.keys():
        item['专利权人'] = '?'
    if '已缴费' not in item.keys():
        item['已缴费'] = '?'
    if '申请号' not in item.keys():
        item['申请号'] = file.split('_')[-2].split('-')[0]
    if '年度年费' in money_li:
        item['费用明细'] = money_li[0]
    return item

